<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Yansongda\Pay\Pay;

class ShoppingOrderController extends ApiController
{

    /**
     * 获取订单列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $status = $request->input("status", 0);
        $page = $request->input("page", 1);

        $limit = $request->input("limit", 10);
        if ($page <= 0) {
            return $this->failed("参数错误");
        }
        if ($limit <= 0 || $limit > 100) {
            return $this->failed("参数错误");
        }
        $where = ['o.is_delete' => 0, 'o.user_id' => $user_id];
        if (!empty($status)) {
            if (!in_array($status, array(1, 2, 3, 4, 5, 6, 7))) {
                return $this->failed("参数错误");
            }
            $where['o.status'] = $status;
        }
        $order_list = DB::table('shopping_order AS o')
            ->leftJoin('pickup_site AS s', 's.id', '=', 'o.site_id')
            ->where($where)
            ->orderBy('id', 'desc')
            ->select('o.id', 'o.order_no','o.goods_num', 'o.is_fresh', 'o.money', 'o.status', 'o.order_time', 's.name as site_name')
            ->skip($limit * ($page -1))
            ->take($limit)
            ->get();

        if (!empty($order_list)) {
            $order_ids = [];
            foreach ($order_list as $list) {
                $order_ids[] = $list->id;
            }
            $order_items = DB::table('shopping_order_items AS i')
                ->leftJoin('goods AS g', 'g.id', '=', 'i.goods_id')
                ->whereIn('i.order_id', $order_ids)
                ->select('i.order_id', 'i.goods_id', 'i.goods_num', 'i.goods_price', 'g.main_pic')
                ->get();
            foreach ($order_list as $key => $order) {
                foreach ($order_items as $item)
                {
                    if ($order->id == $item->order_id) {
                        $order_list[$key]->goods_list[] = $item;
                    }
                }
            }
        } else {
            $order_list = [];
        }

        $count =  DB::table('shopping_order AS o')->where($where)->count();
        return $this->success(['order_list' => $order_list, 'more' => $count > $page * $limit ? true : false]);
    }

    /**
     * 获取订单详情
     * 订单状态：1.未支付（下单未支付），2.未领取（已支付未领取状态）3.已取消(未领取状态下取消/退款订单），4.已领取（完成状态），5.已失效（超过12小时未支付订单），6.已过期（新鲜实物未在规定时间领取），7申请退款 8已退款
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function detail(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $order_no = $request->input("order_no");
        if (empty($order_no)) {
            return $this->failed("参数错误");
        }

        $order = DB::table('shopping_order AS o')
            ->leftJoin('pickup_site AS s', 's.id', '=', 'o.site_id')
            ->select('o.id', 'o.order_no','o.goods_num', 'o.is_fresh', 'o.money', 'o.status', 'o.order_time', 'o.auto_expire_time', 'o.start_pick_time', 'o.end_pick_time', 'o.check_code', 's.name as site_name')
            ->where(['o.order_no' => $order_no, 'o.user_id' => $user_id, 'o.is_delete' => 0])
            ->first();
        if (empty($order)) {
            return $this->failed("参数错误");
        }
        $order_items = DB::table('shopping_order_items AS i')
            ->leftJoin('goods AS g', 'g.id', '=', 'i.goods_id')
            ->where(['i.order_id' => $order->id])
            ->select('i.goods_id', 'i.goods_num', 'i.goods_price', 'g.main_pic', 'g.title')
            ->get();
        $order->goods_list = $order_items;

        //生成二维码
        if ($order->status == 2) {
            $check_code = $order->order_no . '_' . md5($order->order_no . md5($order->check_code));
//            $qr_code = QrCode::generate($check_code);
            $order->qr_code = $check_code;
        }
        return $this->success(['order' => $order]);
    }

    /**
     * 订单支付
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderPay(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $code = $request->input("code");
        $order_no = $request->input("order_no");
        if (empty($order_no)) {
            return $this->failed("参数错误");
        }
        if (empty($code)) {
            return $this->failed("参数错误");
        }
        $order = DB::table('shopping_order')
            ->where(['order_no' => $order_no, 'user_id' => $user_id, 'is_delete' => 0])
            ->first();
        if (empty($order)) {
            return $this->failed("参数错误");
        }
        if ($order->status != 1) { //未支付的订单才可以支付
            return $this->failed("参数错误");
        }

        //获取openid
        $wechat_config = config('pay.wechat');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$wechat_config['miniapp_id']}&secret={$wechat_config['miniapp_secret']}&js_code={$code}&grant_type=authorization_code";
        $client = new Client();
        $req = $client->request('GET', $url);

        $res =  json_decode($req->getBody()->getContents(), true);
        if (empty($res['openid'])) {
            return $this->failed("获取失败");
        }
        $openid = $res['openid'];


        //调用微信支付
        $order = [
            'out_trade_no' => $order->order_no,
            'total_fee' => $order->money * 100,
            'body' => '小厘健康-支付',
            'openid' => $openid,
        ];

        $pay = Pay::wechat($wechat_config)->miniapp($order);
        if (empty($pay)) {
            return $this->failed("提交订单失败");
        }
        return $this->success(['payment' => $pay, 'order' => ['order_no' => $order_no]]);
    }

    /**
     * 申请退款
     *
     * @param Request $request
     */
    public function applyRefund(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $order_no = $request->input("order_no");
        if (empty($order_no)) {
            return $this->failed("参数错误");
        }
        $order = DB::table('shopping_order')
            ->where(['order_no' => $order_no, 'user_id' => $user_id, 'is_delete' => 0])
            ->first();
        if (empty($order)) {
            return $this->failed("参数错误");
        }
        if (!empty($order->is_fresh)) { //新鲜食材不能申请退款
            return $this->failed("新鲜食材不能申请退款");
        }
        if ($order->status != 2) { //已支付未领取的订单才可以申请退款
            return $this->failed("该订单不是未领取状态，不能申请退款");
        }
        $res = DB::table('shopping_order')->where(['order_no' => $order_no])->update(['status' => 6, 'apply_refund_time' => time()]);
        if (empty($res)) {
            return $this->failed("申请退款失败");
        }
        return $this->success("申请退款成功，三日内工作人员将联系您，并返还退款金额");
    }
}
